package cuiyt.collection.list;

import java.lang.reflect.Field;
import java.util.ArrayList;

/**
 * @author cyt
 * @create 2020-09-15 下午 7:41
 */
public class ArrayListDemo {


    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        System.out.println(list.size());
        for (int i = 0; i < 10; i++) {
            list.add(i);
        }

        System.out.println(list.size() + "- >" + getCapacity(list));
        list.add(12);
        list.add(13);
        System.out.println(list.size() + "- >" + getCapacity(list));
        list.add(Integer.MAX_VALUE - 9, 444);
        System.out.println(list.size() + "- >" + getCapacity(list));
    }

    /**
     * 使用反射来获得当前集合中的容量
     *
     * @param list
     * @return
     */
    public static Integer getCapacity(ArrayList list) {
        Integer length = null;
        Class c = list.getClass();
        Field f;
        try {
            f = c.getDeclaredField("elementData");
            f.setAccessible(true);
            Object[] o = (Object[]) f.get(list);
            length = o.length;
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return length;
    }
}
